//
//  UIAttachmentViewController.swift
//  Animator
//
//  Created by liu guoqiang on 16/9/9.
//  Copyright © 2016年 liu guoqiang. All rights reserved.
//

import UIKit

class UIAttachmentViewController: UIViewController,UICollisionBehaviorDelegate {
   
    @IBOutlet weak var attachmentPoint: UIImageView!
    @IBOutlet weak var box: UIImageView!
    @IBOutlet weak var barrier: UIImageView!
    var collision : UICollisionBehavior!
    var animator : UIDynamicAnimator!
    var gravity : UIGravityBehavior!
    var attach : UIAttachmentBehavior!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "吸附行为"
    }

    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        self.animator = UIDynamicAnimator(referenceView: self.view)
        self.gravity = UIGravityBehavior(items: [self.box])
        self.animator.addBehavior(self.gravity)
        
        self.collision = UICollisionBehavior(items: [self.box])
        let width = self.barrier.frame.size.width
        let origin = self.barrier.frame.origin
        self.collision.addBoundaryWithIdentifier("barrier", fromPoint: origin, toPoint: CGPointMake(origin.x+width, origin.y))
        self.collision.translatesReferenceBoundsIntoBoundary = true
        self.collision.collisionDelegate = self
        self.animator.addBehavior(self.collision)
        let itemBehaviour = UIDynamicItemBehavior(items: [self.box])
        itemBehaviour.elasticity = 0.5
        self.animator.addBehavior(itemBehaviour)
    }
    
    internal func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?, atPoint p: CGPoint){
        self.attach = UIAttachmentBehavior(item: self.attachmentPoint, attachedToItem: self.box)
        self.animator.addBehavior(self.attach)
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
